package com.dms.modules.community.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
//
import com.dms.common.security.SecurityUtils;
import com.dms.modules.community.dto.CommunityCommentDTO;
import com.dms.modules.community.dto.CommunityCommentTreeDTO;
import com.dms.modules.community.service.CommunityCommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/v1/community/comment")
@Api(tags = "社区评论接口")
@RequiredArgsConstructor
@Validated
public class CommunityCommentController {

    private final CommunityCommentService commentService;

    @PostMapping("/create")
    @ApiOperation("创建评论")
    public ApiResponse<Void> createComment(
            @RequestParam Long postId,
            @RequestParam(required = false) Long parentId,
            @RequestParam String content) {
        try {
            CommunityCommentDTO commentDTO = new CommunityCommentDTO();
            commentDTO.setPostId(postId);
            commentDTO.setParentId(parentId);
            commentDTO.setContent(content);
            commentDTO.setUserId(SecurityUtils.getCurrentUserId());
            
            commentService.createComment(commentDTO);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("创建评论失败: postId={}, parentId={}, error={}", postId, parentId, e.getMessage(), e);
            return ApiResponse.error(e);
        }
    }

    @DeleteMapping("/{commentId}")
    @ApiOperation("删除评论")
    public ApiResponse<Void> deleteComment(@PathVariable Long commentId) {
        try {
            commentService.deleteComment(commentId);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("删除评论失败: commentId={}, error={}", commentId, e.getMessage(), e);
            return ApiResponse.error(e);
        }
    }

    @PostMapping("/{commentId}/like")
    @ApiOperation("点赞/取消点赞评论")
    public ApiResponse<Void> likeComment(@PathVariable Long commentId) {
        try {
            commentService.likeComment(commentId);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("评论点赞操作失败: commentId={}, error={}", commentId, e.getMessage(), e);
            return ApiResponse.error(e);
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取评论列表（树状结构）", notes = "返回树状结构的评论列表，包含所有层级的回复")
    public ApiResponse<IPage<CommunityCommentTreeDTO>> getCommentList(
            @RequestParam Long postId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 1. 获取一级评论（分页）
            Page<CommunityCommentTreeDTO> page = new Page<>(current, size);
            IPage<CommunityCommentTreeDTO> comments = commentService.getCommentList(postId, userId, page);
            
            if (!comments.getRecords().isEmpty()) {
                // 2. 一次性获取所有相关的回复
                List<Long> commentIds = comments.getRecords().stream()
                    .map(CommunityCommentTreeDTO::getId)
                    .collect(Collectors.toList());
                
                List<CommunityCommentTreeDTO> allReplies = commentService.getAllCommentReplies(postId, commentIds, userId);
                
                // 3. 构建回复树
                Map<Long, List<CommunityCommentTreeDTO>> replyMap = new HashMap<>();
                for (CommunityCommentTreeDTO reply : allReplies) {
                    replyMap.computeIfAbsent(reply.getParentId(), k -> new ArrayList<>()).add(reply);
                }
                
                // 4. 设置回复树
                for (CommunityCommentTreeDTO comment : comments.getRecords()) {
                    buildCommentTree(comment, replyMap);
                }
            }
            
            return ApiResponse.success(comments);
        } catch (Exception e) {
            log.error("获取评论列表失败: postId={}, error={}", postId, e.getMessage(), e);
            return ApiResponse.error(e);
        }
    }
    
    /**
     * 递归构建评论树
     */
    private void buildCommentTree(CommunityCommentTreeDTO comment, Map<Long, List<CommunityCommentTreeDTO>> replyMap) {
        List<CommunityCommentTreeDTO> children = replyMap.getOrDefault(comment.getId(), new ArrayList<>());
        comment.setChildren(children);
        comment.setReplyCount(children.size());
        
        // 递归构建子回复的树
        for (CommunityCommentTreeDTO child : children) {
            buildCommentTree(child, replyMap);
        }
    }
} 